/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.ws.server.serialization;

import org.bmi.gwt.ws.shared.PayloadSerializer;

import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.impl.AbstractSerializationStream;
import com.google.gwt.user.server.rpc.SerializationPolicyProvider;
import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader;
import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter;

/**
 * Server version of the class responsible of object serialization and
 * deserialization.
 * 
 * @author Marco Tamburelli
 * 
 * @param <T>
 */
public abstract class ServerPayloadSerializer<T extends IsSerializable> implements PayloadSerializer<T>
{
	@SuppressWarnings("unchecked")
	@Override
	public T deserialize(String payload) throws SerializationException
	{
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(classLoader,
				getSerializationPolicy());

		streamReader.prepareToRead(payload);

		String className = SerializationTool.maybeDeobfuscate(streamReader, streamReader.readString());

		try
		{
			Class<?> type = SerializationTool.getClassFromSerializedName(className, classLoader);

			return (T) streamReader.deserializeValue(type);
		}
		catch (ClassNotFoundException e)
		{
			throw new SerializationException("Receved object is of an unknown type '" + className + "'", e);
		}
		catch (ClassCastException e)
		{
			throw new SerializationException("Receved object class '" + className
					+ "' doesn't match the expected class", e);
		}
	}

	@Override
	public String serialize(T obj) throws SerializationException
	{
		Class<?> classType = obj.getClass();
		Class<?> actualClassType;

		if (classType.isPrimitive())
			actualClassType = SerializationTool.getPrimitiveClassFromWrapper(classType);
		else
			actualClassType = classType;

		ServerSerializationStreamWriter stream = new ServerSerializationStreamWriter(
				SerializationTool.getDefaultSerializationPolicy());
		stream.setFlags(AbstractSerializationStream.DEFAULT_FLAGS);

		stream.prepareToWrite();

		if (actualClassType != void.class) stream.serializeValue(obj, actualClassType);

		return stream.toString();
	}

	/**
	 * Force subclasses to provide a {@link SerializationPolicyProvider} object
	 * to help serialization and deserialization operations.
	 * 
	 * @return
	 */
	protected abstract SerializationPolicyProvider getSerializationPolicy();
}
